package com.ruoyi.web.dao.BT;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.web.domain.BT.AdvancedTorrentParam;
import com.ruoyi.web.domain.BT.TorrentEntity;
import com.ruoyi.web.domain.BT.TorrentParam;
import org.apache.ibatis.annotations.*;
import org.apache.poi.ss.formula.functions.T;

import java.util.List;

@Mapper
public interface TorrentDao extends BaseMapper<TorrentEntity> {
    List<TorrentEntity> search(TorrentParam param);
    @Insert("INSERT INTO bt_torrent (\n" +
            "    info_hash, name, filename, title, subheading, \n" +
            "    cover, description, category, status, file_status, \n" +
            "    reviewer, create_time, update_time, owner, size, \n" +
            "    type, file_count, comments, views, hits, \n" +
            "    visible, anonymous, leechers, seeders, completions, \n" +
            "    remark\n" +
            ") VALUES (\n" +
            "    #{infoHash}, #{name}, #{filename}, #{title}, #{subheading}, \n" +
            "    #{cover}, #{description}, #{category}, #{status}, #{fileStatus}, \n" +
            "    #{reviewer}, #{createTime}, #{updateTime}, #{owner}, #{size}, \n" +
            "    #{type}, #{fileCount}, #{comments}, #{views}, #{hits}, \n" +
            "    #{visible}, #{anonymous}, #{leechers}, #{seeders}, #{completions}, \n" +
            "    #{remark}\n" +
            ")")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insert(TorrentEntity entity);

    @Select("select * from bt_torrent where id=#{id}")
    TorrentEntity selectById(int id);

    @Select("SELECT COUNT(*) FROM bt_torrent WHERE info_hash = #{infoHash}")
    long selectCountByInfoHash(byte[] infoHash);

    @Select("SELECT COUNT(*) FROM bt_torrent")
    int countId();

    default List<TorrentEntity> advancedSearch(AdvancedTorrentParam param) {
        QueryWrapper<TorrentEntity> wrapper = new QueryWrapper<>();

        // 构建基础查询条件
        if (param.getCategory() != null) {
            wrapper.eq("category", param.getCategory());
        }
        if (param.getStatus() != null) {
            wrapper.eq("status", param.getStatus());
        }

        // 处理排序
        if (StringUtils.isNotBlank(param.getSortField())) {
            // 安全映射：防止SQL注入
            String orderByField = mapSortField(param.getSortField());
            if (orderByField != null) {
                boolean isAsc = "asc".equalsIgnoreCase(param.getSortDirection());
                wrapper.orderBy(true, isAsc, orderByField);
            }
        }

        return this.selectList(wrapper);
    }

    /**
     * 安全映射排序字段（防止SQL注入）
     */
    default String mapSortField(String sortField) {
        switch (sortField) {
            case "createTime":
                return "create_time";
            case "updateTime":
                return "update_time";
            case "completions":
                return "completions";
            case "leechers":
                return "leechers";
            case "seeders":
                return "seeders";
            default:
                return null; // 忽略非法字段
        }
    }

    @Update("UPDATE bt_torrent SET leechers = leechers + 1 WHERE id = #{id}")
    int incrementLeechers(@Param("id") Integer id);

    @Select("select id from bt_torrent where info_hash=#{infoHash} ")
    int getTorrentIdByHash(byte[] infoHash);
}
